'use strict';
const db = uniCloud.database();

exports.main = async (event, context) => {
  const { pk_id, user_id } = event;
  try {
    if (!pk_id || !user_id) {
      return { code: -1, msg: 'PK ID 或用户ID不能为空' };
    }

    const pkCollection = db.collection('pk_records');
    const pkRes = await pkCollection.doc(pk_id).get();
    if (!pkRes.data.length) {
      return { code: -1, msg: 'PK记录不存在' };
    }
    const pk = pkRes.data[0];

    if (pk.challenger_id !== user_id && pk.opponent_id !== user_id) {
      return { code: -1, msg: '无权查看PK状态' };
    }

    const opponent_id = pk.challenger_id === user_id ? pk.opponent_id : pk.challenger_id;
    const opponent = opponent_id
      ? (await db.collection('users').where({ _id: opponent_id }).get()).data[0]
      : { name: '未知', _id: null };

    console.log('获取PK状态:', { pk_id, status: pk.status }); // 调试
    return {
      code: 0,
      data: {
        status: pk.status,
        winner_id: pk.winner_id,
        opponent_score: pk.challenger_id === user_id ? pk.opponent_score : pk.challenger_score,
        questions: pk.questions,
        opponent: { name: opponent.name || '未知', id: opponent._id },
        exited_by: pk.exited_by
      },
      msg: '获取PK状态成功'
    };
  } catch (e) {
    console.error('获取PK状态失败:', e);
    return { code: -1, msg: `获取PK状态失败: ${e.message || '未知错误'}` };
  }
};